import React, { useState, useEffect } from "react";
import { Tabs, Form, Input, Space, Button, Row, Col, message } from "antd";
import { ArrowLeftOutlined, PlusOutlined} from '@ant-design/icons';
import cmdbres from "@/data/cmdbres";
import request, {requestIAM} from '@/utils/request';
import hcpUtils from "@/utils/hcpUtils";
import { CmdbContent } from "@/components";
import TemplateModal from "./templateModal";
import "./index.less"
const { TabPane } = Tabs;

const user = hcpUtils.getUser();
const CreateClusterTemplate = ({ history, match, location }) => {
    const biz = location?.state?.biz;
    const template = location?.state?.template;
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [showModal, setShowModal] = useState(false);

    const onFinish = async (fieldsValue) => {
        if(!(biz && biz.cm_unid)) {
			message.warning("请确认是否创建业务！");
			return;
		}
        setLoading(true);
        const {name, serviceTemplateIds} = fieldsValue;
        let ids = [];
        serviceTemplateIds.map(item=> {
            if(item.id) ids.push(item.id);
        });
        const url = template && template.id ? cmdbres.updateSetTemplate(template.id) : cmdbres.createSetTemplate;
        const tip = template && template.id ? '修改' : '创建';
        let res = await request({
			...url,
			data: {
                bizId: biz.cm_unid,
                name,
                serviceTemplateIds: ids,
                author: user.staffName
            }
		});
		setLoading(false);
		if (res && res.code == 200) {
			handleClose();
			message.success(`${tip}服务模版成功！`);
			if (typeof onCreateFinish == "function") onCreateFinish(res);
		}
    }

    const handleClose = () => {
        history.push({pathname: '/business/clusterTemplate'});
    }

    const view = (index) => {
        const list = form.getFieldValue('serviceTemplateIds');
        const _item = list[index];
        console.log(_item);
    }

    useEffect(() => {
        if(template) {
            form.setFieldsValue({
                name: template.name
            })
        }
    }, [template])
    
    return (
        <CmdbContent>
            <div className="cmdb_host_pane">
                <div className="breadcrumbs-layout">
                    <h3>
                        <ArrowLeftOutlined 
                            onClick={handleClose}
                        /> 
                        {template ? '修改集群模板' : '创建集群模板'}
                        
                    </h3>
                </div>
                <Form
                    className="hcp-drawer-form"
                    form={form}
                    labelCol={{ span: 5}}
                    wrapperCol={{ span: 10 }}
                    name="basic"
                    onFinish={onFinish}
                >
                    <Form.Item 
                        label="模板名称" 
                        name="name" 
                        rules={[{required: true,message: '请输入模板名称'}]}
                    >
                        <Input placeholder="请输入模板名称" maxLength={128} />
                    </Form.Item>
                    <Form.Item label="服务模板" required style={{marginBottom: 0}}>
                    <Form.List 
                        name="serviceTemplateIds"
                        rules={[
                            {
                            validator: async (_, service_template_ids) => {
                                if (!service_template_ids || service_template_ids.length < 1) {
                                return Promise.reject(new Error('至少要添加一个服务模板'));
                                }
                            },
                            },
                        ]}
                    >
                        {(fields, { add, remove }, { errors }) => (
                            <>
                            {fields.map((field, index) => (
                                <Row key={index}>
                                    <Col span={20}>
                                        <Form.Item
                                            name={[field.name, 'name']}
                                            rules={[{required: true,message: '请选择源模型Key'}]}
                                            wrapperCol={24}
                                        >
                                            <Input readOnly/>
                                        </Form.Item>
                                    </Col>
                                    {/* <Col span={2} className="text-center">
                                        <Button
                                            type="link"
                                            onClick={() => {view(index)}}
                                        >
                                            查看
                                        </Button>
                                    </Col> */}
                                    <Col span={2} className="text-center">
                                        <Button
                                            type="link"
                                            onClick={() => {remove(field.name)}}
                                        >
                                            删除
                                        </Button>
                                    </Col>
                                </Row>
                            ))}
                            <Form.Item>
                                <Button
                                    type="dashed"
                                    onClick={() => setShowModal(true)}
                                    style={{ width: '60%' }}
                                    icon={<PlusOutlined />}
                                >
                                    添加服务模版
                                </Button>
                                <Form.ErrorList errors={errors} />
                            </Form.Item>
                            <TemplateModal
                                info={template}
                                biz={biz}
                                visible={showModal}
                                setVisible={setShowModal}
                                getDeFaultValue={()=> {
                                    const serviceTemplateIds = form.getFieldValue('serviceTemplateIds') || [];
                                    return serviceTemplateIds.map(item=> item.id);
                                }}
                                onAddFinish={(list)=> {
                                    if(list) {
                                        add();
                                        form.setFieldsValue({ serviceTemplateIds: list });
                                    }
                                }}
                                history={history}
                            />
                            </>
                        )}
                    </Form.List>
                    </Form.Item>
                    <div className="modal-body-footer" style={{paddingTop: "12px",  position: 'absolute', bottom: 10}}>
                        <Space>
                            <Button type="primary" htmlType="submit" loading={loading}>提交</Button>
                            <Button onClick={handleClose}>取消</Button>
                        </Space>
                    </div>
                </Form>
            </div>
        </CmdbContent>
    )
}

export default CreateClusterTemplate;